<template>
  <div id="mainedit">
    <div class="topbar clearfix pr">
      <div class="logo fl"><a href="http://www.zhangu365.com/"><img src="http://www.zhangu365.com/static/images/logowrite.png"></a></div>
      <div class="edit1 fl">
        <a class="file" @click="goMyWorkList">文件</a>
        <a class="revoke" @click="undo">撤销</a>
        <a class="recover" @click="redo">恢复</a>
      </div>
      <div class="title fl pa">
        标题 : <div class="inputwrap fr"><Input type="text" placeholder="设置作品标题" :maxlength="48" v-model="sceneTitle" @on-change="sceneTitleChange"></Input></div>
      </div>
      <div class="help fr">
        <!-- <a class="course" href="#">教程</a> -->
        <a class="service" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2850203338&amp;site=qq&amp;menu=yes" target="_blank">客服</a>
      </div>
      <div class="tips fr" v-text="sceneTime"></div>
      <div class="edit2 fr">
        <a class="release" @click="save">保存</a>
        <a class="download" @click="publishClick">下载</a>
      </div>
    </div>

    <!-- <pagelist :bg-grid-status="bgGridStatus"></pagelist> -->
    <rightfunc></rightfunc>
    <mainbody v-on:change-status="changeStatus" v-on:item-click="itemClick"></mainbody>


    <keep-alive>
      <templatefunc v-if="rightTabIndex == 0"></templatefunc>
      <textfunc v-if="rightTabIndex == 1"></textfunc>
      <picfunc v-if="rightTabIndex == 2"></picfunc>
      <!-- <picedit v-if="rightTabIndex == 20"></picedit> -->
      <backgroundfunc v-if="rightTabIndex == 3"></backgroundfunc>
      <shapefunc v-if="rightTabIndex == 4"></shapefunc>
      <musicfunc v-if="rightTabIndex == 5"></musicfunc>

      <formfunc v-if="rightTabIndex == 6"></formfunc>
      <forminputfunc v-if="rightTabIndex == 61"></forminputfunc>
      <formbuttonfunc v-if="rightTabIndex == 62"></formbuttonfunc>

      <interactionfunc v-if="rightTabIndex == 7"></interactionfunc>
      <!--<thumbsupfunc v-if="rightTabIndex == 71"></thumbsupfunc>-->
      <!--<linkfunc v-if="rightTabIndex == 72"></linkfunc>-->
      <telephonefunc v-if="rightTabIndex == 73"></telephonefunc>
      <countdownfunc v-if="rightTabIndex == 7"></countdownfunc>

      <newlogofunc v-if="rightTabIndex == 8"></newlogofunc>

    </keep-alive>
    <pastk v-if="showSet" :show-set="showSet" :img-file="imgFile" v-on:close="showSet=false" :auto-play="sceneInfo" :user-vip="userVip"></pastk>
    <logintk v-show="showLogin" :show-login="showLogin" v-on:close="showLogin=false" @save="save"></logintk>
    <!-- <buytk v-if="showBuy"></buytk> -->
    <!-- <text-tool-bar></text-tool-bar> -->
    <Modal
      v-model="showModal1"
      title="提示"
      @on-ok="goToBack"
      width="300">
      <p>当前场景还未保存,是否返回上一页?</p>
    </Modal>
    <!-- <Modal
        v-model="showModal2"
        title="提示"
        @on-ok="goToBack"
        width="300">
        <p>是否保存当前场景?</p>
    </Modal> -->
  </div>

</template>

<script type="text/javascript">
  import {mapActions, mapGetters} from 'vuex'
  import api from '../api/index.js'
  import Util from '../Util/index.js'

  import pagelist from './PageList'
  import rightfunc from './RightFunc'
  import mainbody from './MainBody'
  import templatefunc from './TemplateFunc'
  import textfunc from './TextFunc'
  import picfunc from './PicFunc'
  import picedit from './PicEdit'
  import backgroundfunc from './BackgroundFunc'
  import shapefunc from './ShapeFunc'
  import musicfunc from './MusicFunc'
  import forminputfunc from './FormInputFunc'
  import formbuttonfunc from './FormButtonFunc'
  import formfunc from './FormFunc'
  import interactionfunc from './InteractionFunc'
  import thumbsupfunc from './ThumbsupFunc'
  import telephonefunc from './TelephoneFunc'
  import linkfunc from './LinkFunc'
  import countdownfunc from './CountdownFunc'

  import newlogofunc from './NewlogoFunc'

  import pastk from './PreviewAndSetting'
  import buytk from './common/BuyFunc'
  import logintk from './common/LoginFunc'
  import textToolBar from './common/TextToolBar'

  export default {
    name: 'mainedit',
    computed: {
      ...mapGetters([
        "rightTabIndex",
        "pagesData",
        "checkedItemData"
      ])
    },
    watch: {
      pagesData: function (newpagesData) {
        // console.log("我被改变啦")

        this.isChange = true;
        // debugger
      },
      checkedItemData: function (newCheckedItemData) {
        console.log("check")
        this.isChange = true;
      }

    },
    components: {
      ...mapGetters([
        "sceneInfo",
      ]),
      pagelist,
      rightfunc,
      mainbody,
      templatefunc,
      textfunc,
      picfunc,
      picedit,
      backgroundfunc,
      shapefunc,
      musicfunc,
      formfunc,
      forminputfunc,
      formbuttonfunc,
      interactionfunc,
      thumbsupfunc,
      telephonefunc,
      linkfunc,
      countdownfunc,
      newlogofunc,
      pastk,
      buytk,
      logintk,
      textToolBar
    },
    data(){

      return {
        showModal1: false,
        showModal2: false,
        bgGridStatus: true,
        showSet: false,
        isChange: false,
        showBuy: true,
        showLogin:false,
        imgFile:'',
	      testIndex: 0,
        sceneTitle:'',
        sceneTime:'',
        userVip:0
      }
    },
    mounted: function () {
      this.checkedItemData
//      console.log(this.checkedItemData)
      //debugger
      //console.log(this.$store.state.workData);
      
      //debugger;
      //this.sceneTitle = this.$store.state;
    },
    created () {
      this.initBaseData()

      // this.initUserData();
    },
    methods: {
      //撤销
      undo(){
        if (this.testIndex >= this.$store.state.historyList.length - 1) {

          return;
        }
        this.testIndex += 1
        var index = this.$store.state.historyList.length - 1 - this.testIndex;
//        console.log(this.testIndex)
//        console.log(index)
//        index=index-1;
        if (index <= -1) {
          return;
        }
        //0 -> 1 ->2 ->3

        var params = this.$store.state.historyList[index]
        params = JSON.parse(params)
        this.$store.dispatch('updateCurrentdata', params)

      },

      redo(){

        if (this.testIndex == 0) {

          return;
        }
        var index = this.$store.state.historyList.length - this.testIndex;

        this.testIndex -= 1
//        console.log(this.testIndex)
//        console.log(index)
        var params = this.$store.state.historyList[index]
        params = JSON.parse(params)
        this.$store.dispatch('updateCurrentdata', params)

      },
      //初始化数据

      html_decode(str){
        return Util.htmlDecode(str);
      },
      goMyWorkList(){

        if (this.isChange == true) {

          this.showModal1 = true
        } else {


          this.goToBack();
        }

      },
      initBaseData(){

        this.$http.get(api.getUser()).then(res => {
          if (res.data.code == 200) {
            if (res.data.status) {
              //debugger
              this.$store.dispatch('initUserData', res.data)
              this.userVip = res.data.userinfo.vip;
            }
            //debugger
            //console.log(this.$route.query.sceneid);
            this.$http.get(api.getScenepageBySceneID(this.$route.query.sceneid)).then(res => {
              if (res.data.code == 200) {
                if (res.data.status) {
                  //debugger
                  this.$store.dispatch('initData', res.data)
                  this.$store.dispatch("pushHistory");
                  //赋值标题和时间
                  this.sceneTitle = this.$store.state.workData.sceneinfo['name'];
                  this.sceneTime = this.$store.state.workData.sceneinfo['publish_time']+'更新';
                } else {
                  this.$Message.error(res.data.msg);
                }
              } else {
                this.$Message.error('网络开小差啦~');
              }
            }).catch(error => {
              // debugger    // 错误处理
//		        console.log(error)
              this.$Message.error('网络开小差啦~');
            })
          }
        }).catch(error => {
          this.$Message.error('获取用户信息失败~');
        })
      },
      changeStatus(){
        this.bgGridStatus = !this.bgGridStatus
      },
      itemClick(itemType){

        // debugger

        switch (itemType) {
          //文字
          case 25:
            this.tabIndex = 1;
            break;
          //图片
          case 4:
            this.tabIndex = 2;
            break;
        }
      },
      showSetClick(){

        this.showSet = true;
      },
      publishClick(){
        var _self = this;
        var dataLists = this.$store.state.workData.pages;
        var sceneinfo = this.$store.state.workData.sceneinfo;

        var tip = this.$Message.loading({
          content: '生成中...',
          duration: 0
        });
        this.$http({

          method: 'post',
          url: api.getScenepageimg(),
          data: {
            lists: dataLists,
            sceneinfo: sceneinfo,
            sceneid: this.$route.query.sceneid,
          },

        }).then(res => {
          setTimeout(tip, 1);
          // debugger
          if (res.data.code == 200) {

            this.sceneTime = res.data.publish_time+'更新';
            // this.showSet

            if (res.data.status == true) {
              isShow = false;//控制刷新页面时受否弹出刷新提示框
              this.$Message.success('发布成功!');
              this.isChange = false
              _self.imgFile = res.data.imgfile+"?t="+new Date().getTime();
              _self.showSet = true;
              _self.userVip = res.data.vip;

              if(res.data.rs > 0){
                var newurl = this.changeURLArg(window.location.href,'sceneid',res.data.rs);
                window.history.pushState({},0,newurl);
                this.$route.query.sceneid = res.data.rs;
                this.initBaseData();
                this.$store.state.workData.sceneinfo['id'] = res.data.rs;
              }

            } else {
              if(res.data.msg == '未登录'){
                _self.showLogin = true;
                console.log('登录弹框');
              }else{
                this.$Message.error(res.data.msg);
              }

              
            }


          } else {

            this.$Message.error('网络开小差啦~');
          }

        }).catch(error => {
          // alert(error);
          setTimeout(tip, 1);
          this.$Message.error('网络开小差啦~');
        });


      },
      sceneTitleChange(){
        var text = this.sceneTitle;
        text = this.html_decode(text);
        var params = {};
        params.keys = ["name"];
        params.values = [text];
        this.$store.dispatch("changeSceneInfo", params)
      },
      goToBack(){
        // debugger
        // history.back(-1);
        // this.modal5 = true
        window.location.href = "http://www.zhangu365.com/posters.html";
//        window.location.href = "http://www.jiaobu365.com/works.html";

      },
      save(){
        //debugger
        var _self = this;
        var dataLists = this.$store.state.workData.pages;
        for (var i = 0; i < dataLists.length; i++) {
          for (var j = 0; j < dataLists[i].elements.length; j++) {
            if (dataLists[i].elements[j].type == "2" || dataLists[i].elements[j].type == "5") {
//                   dataLists[i].elements[j].content=this.html_decode(dataLists[i].elements[j].content);
              var params = {};
              params.index = i;
              params.index1 = j;
              params.data = this.html_decode(dataLists[i].elements[j].content);
              this.$store.dispatch("processData", params)
            }
          }
        }
        var sceneinfo = this.$store.state.workData.sceneinfo;
        var params = {};
        params.name = this.html_decode(sceneinfo.name);
        params.desc = this.html_decode(sceneinfo.desc);
        this.$store.dispatch("checkScenesData", params)
        var tip = this.$Message.loading({
          content: '保存中...',
          duration: 0
        });

        this.$http({
          method: 'post',
          url: api.getScenepage(),
          data: {
            lists: dataLists,
            sceneinfo: sceneinfo,
            sceneid: this.$route.query.sceneid,
          },

        }).then(res => {
          setTimeout(tip, 1);
          //debugger
          if (res.data.code == 200) {


            // this.showSet
 
            if (res.data.status == true) {

              this.$Message.success('保存成功!');
              this.sceneTime = res.data.publish_time+'更新';
              this.isChange = false
              //如果是新纪录更新url地址
              if(res.data.rs > 0){
                var newurl = this.changeURLArg(window.location.href,'sceneid',res.data.rs);
                window.history.pushState({},0,newurl);
                this.$route.query.sceneid = res.data.rs;
                this.initBaseData();
              }

            } else {

              if(res.data.msg == '未登录'){
                this.showLogin = true;
                console.log('登录弹框');
              }else{
                this.$Message.error(res.data.msg);
              }
            }


          } else {

            this.$Message.error('网络开小差啦~');
          }

        }).catch(error => {
          // alert(error);
          setTimeout(tip, 1);
          this.$Message.error('网络开小差啦~');
        });
      },
      html_decodes(str){
        var tt;
        for (var i = 0; i < str.length; i++) {
          tt = str.replace(/&nbsp;/g, " ");
        }
//        str.replace(/&nbsp;/g, " ");
//        console.log(tt)
        return tt;
      },

      changeURLArg(url,arg,arg_val){ 
          var pattern=arg+'=([^&]*)'; 
          var replaceText=arg+'='+arg_val; 
          if(url.match(pattern)){ 
              var tmp='/('+ arg+'=)([^&]*)/gi'; 
              tmp=url.replace(eval(tmp),replaceText); 
              return tmp; 
          }else{ 
              if(url.match('[\?]')){ 
                  return url+'&'+replaceText; 
              }else{ 
                  return url+'?'+replaceText; 
              } 
          } 
          return url+'\n'+arg+'\n'+arg_val; 
      }  


    }
  }
</script>

<style type="text/css">
  .rightbody {
    position: fixed;
    width: 330px;
    top: 54px;
    bottom: 0;
    left: 65px;
    background: #fff;
    box-shadow: -3px 0 5px 0 rgba(213, 213, 213, .35);
    overflow-y: auto;
  }

  .topbar {
    position: fixed;
    height: 54px;
    width: 100%;
    background: #23D7BC;
  }

  /*.topbar {*/
  /*position: fixed;*/
  /*height: 50px;*/
  /*width: 100%;*/
  /*background: #4c9e9c;*/
  /*}*/

  .topbar a {
    font-size: 14px;
    color: #fff;
    height: 30px;
    line-height: 30px;
  }

  .topbar .logo {
    margin: 15px 30px 0;
  }

  /**
  脚步
   */

  /*.logo a{*/
  /*margin-top: 0px;*/
  /*}*/
  /*.logo img{*/
  /*height: 55px;*/
  /*}*/

  /**
 结束
   */
  .topbar .back a {
    background: url(../assets/images/ticon1.png) no-repeat center left;
  }

  .topbar .publish {
    padding: 0 15px;
    margin: 10px;
    border-radius: 3px;
    background: #fff;
  }

  .topbar .publish a {
    margin: 0;
    background: url(../assets/images/ticon4.png) no-repeat center left #fff;
    color: #1abd9b;
  }

  .topbar .preview a {
    background: url(../assets/images/ticon3.png) no-repeat center left;
  }

  .topbar .save a {
    background: url(../assets/images/ticon2.png) no-repeat center left;
  }

.topbar .edit1{margin:11px 0 0 20px;}
.topbar .edit1 a{float: left;color: #fff;font-size: 13px;text-align: center;padding-top: 13px;margin: 0 20px;}
.topbar .edit1 a.file{background: url(../assets/images/ticon1.png) no-repeat center top;}
.topbar .edit1 a.revoke{background: url(../assets/images/ticon2.png) no-repeat center top;}
.topbar .edit1 a.recover{background: url(../assets/images/ticon3.png) no-repeat center top;}
.topbar .edit2{margin-right:80px;}
.topbar .edit2 a{float:left;width:56px;height: 32px;border: 2px solid #fff;color: #fff;border-radius: 30px;font-size: 13px;line-height: 30px;text-align: center;margin: 10px;padding: 0;}
.topbar .title{color: #c2fff6;font-size: 16px;height: 30px;line-height:30px;top: 12px;width: 266px;left: 50%;margin-left: -133px;}
.topbar .title input{display: block;width: 225px;height: 28px;border:0;border-bottom: 2px dashed #20bba3;padding: 0;padding-right: 23px;background: url(../assets/images/ticon4.png) no-repeat 205px center;text-indent: 12px;color: #c2fff6;font-size: 16px;}
.topbar .tips{font-size: 14px;color: #fff;height: 24px;line-height: 24px;margin-top: 15px;margin-right: 100px;}
.topbar .help{margin-right: 40px;}
.topbar .help a{float: left;font-size: 15px;color: #fff;height: 24px;line-height: 24px; margin:15px;}


:-moz-placeholder {color: #c2fff6; opacity:1;}
::-moz-placeholder {color: #c2fff6;opacity:1;}
input:-ms-input-placeholder{color: #c2fff6;opacity:1;}
input::-webkit-input-placeholder{color: #c2fff6;opacity:1;}
</style>
